package com.ksy.common.qqapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Keep;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.barlibrary.ImmersionBar;
import com.ksy.common.activity.CommonBaseActivity;
import com.ksy.common.login.QQInfo;
import com.ksy.common.utils.Constants;
import com.ksy.common.utils.LogTool;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import static com.ksy.common.login.LoginPlatform.Login_Code_QQ_Cancel;
import static com.ksy.common.login.LoginPlatform.Login_Code_QQ_Error;
import static com.ksy.common.login.LoginPlatform.Login_Code_QQ_Success;


public class QQLoginActivity extends CommonBaseActivity {
    private Tencent mTencent;
    private IUiListener loginListener;
    private IUiListener userInfoListener;


    @Override
    protected boolean isShowRoot() {
        return false;
    }

    @Override
    protected void initImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setResult(Login_Code_QQ_Cancel);
        mTencent = Tencent.createInstance(Constants.QQID, QQLoginActivity.this);
        boolean qqInstalled = mTencent.isQQInstalled(QQLoginActivity.this);
        if (!qqInstalled) {
            onError("请先安装QQ");
            return;
        }
        loginListener = new BaseUiListener(Type.Login);
        userInfoListener = new BaseUiListener(Type.UserInfo);
        login();
    }

    public void login() {
        if (!mTencent.isSessionValid()) {
            mTencent.login(this, "all", loginListener);
        } else {
            mTencent.logout(QQLoginActivity.this);
            mTencent.login(this, "all", loginListener);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Keep
    enum Type {
        Login,
        UserInfo
    }

    private class BaseUiListener implements IUiListener {
        private final Type type;

        public BaseUiListener(Type type) {
            this.type = type;
        }

        @Override
        public void onComplete(Object response) {
            if (null == response || !(response instanceof JSONObject)) {
                QQLoginActivity.this.onFail(type);
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (jsonResponse.length() == 0) {
                QQLoginActivity.this.onFail(type);
                return;
            }
            QQLoginActivity.this.onSuccess(type, jsonResponse);
        }

        @Override
        public void onError(UiError uiError) {
            QQLoginActivity.this.onFail(type);
        }

        @Override
        public void onCancel() {
            QQLoginActivity.this.onCancel();
        }

    }

    private void onSuccess(Type type, JSONObject jsonResponse) {
        if (type == Type.Login) {
            LogTool.w("Login  " + jsonResponse);
            try {
                String token = jsonResponse.optString(com.tencent.connect.common.Constants.PARAM_ACCESS_TOKEN);
                String expires = jsonResponse.optString(com.tencent.connect.common.Constants.PARAM_EXPIRES_IN);
                String openId = jsonResponse.optString(com.tencent.connect.common.Constants.PARAM_OPEN_ID);
                if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
                    mTencent.setAccessToken(token, expires);
                    mTencent.setOpenId(openId);
                }
                UserInfo mInfo = new UserInfo(QQLoginActivity.this, mTencent.getQQToken());
                mInfo.getUserInfo(userInfoListener);
            } catch (Exception e) {
                onFail(type);
            }
        } else {
            LogTool.w("userInfo " + jsonResponse);
            try {
                Gson gson = new Gson();
                String openId = mTencent.getOpenId();
                QQInfo qqInfo = gson.fromJson(jsonResponse.toString(), QQInfo.class);
                qqInfo.openid = openId;
                QQLoginActivity.this.onSuccess(qqInfo);
                return;
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
            QQLoginActivity.this.onError("获取QQ信息失败");

        }
    }

    private void onFail(Type type) {
        QQLoginActivity.this.onError(type == Type.Login ? "登陆QQ失败" : "获取QQ信息失败");

    }

    private void onSuccess(QQInfo qqInfo) {
        Intent intent = new Intent();
        intent.putExtra("qqInfo", qqInfo);
        setResult(Login_Code_QQ_Success, intent);
        destroy();
    }

    private void onError(String msg) {
        Intent intent = new Intent();
        intent.putExtra("errorMsg", msg);
        setResult(Login_Code_QQ_Error, intent);
        destroy();
    }

    private void onCancel() {
        setResult(Login_Code_QQ_Cancel);
        destroy();
    }

    private void destroy() {
        finish();
        overridePendingTransition(0, 0);
    }
}